<?php
// +----------------------------------------------------------------------
// | [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 
// +----------------------------------------------------------------------
namespace app\api\service;

use app\lib\exception\ForbiddenException;
use app\lib\exception\TokenException;
use app\lib\enum\ScopeEnum;
use think\facade\Request;
use think\facade\Cache;
use think\Exception;

class Token
{
  // 生成令牌key
  public static function generateToken()
  {
    // 32个字符组成一组随机字符串
    $randChars = getRandChar(32);
    // 用三组字符串进行md5加密
    $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
    // salt 盐
    $salt = config('secure.token_salt');
    return md5($randChars.$timestamp.$salt);
  }  

  // 获取令牌中的信息
  public static function getCurrentTokenVar($key)
  {
    $token = Request::header('token');
    $vars = Cache::get($token);
    if(!$vars) {
      throw new TokenException();
    }
    else {
      if (!is_array($vars)) {
        $vars = json_decode($vars,true);
      }
      if (array_key_exists($key, $vars)) {
        return $vars[$key];
      }
      else {
        throw new Exception('尝试获取的Token变量并不存在');
      }
    }
  }

  // 获取用户uid
  public static function getCurrentUid()
  {
    // token
    $uid = self::getCurrentTokenVar('uid');
    return $uid;
  }

  // 用户和CMS管理员都可以访问的接口权限
  public static function needPrimaryScope()
  {
    $scope = self::getCurrentTokenVar('scope');
    if ($scope) {
      if ($scope >= ScopeEnum::User) {
        return true;
      }
      else {
        throw new ForbiddenException();
      }
    }
    else {
      throw new TokenException();
    }
  }

  // 只有用户才能访问的接口权限
  public static function needExclusiveScope()
  {
    $scope = self::getCurrentTokenVar('scope');
    if ($scope) {
      if ($scope == ScopeEnum::User) {
        return true;
      }
      else {
        throw new ForbiddenException();
      }
    }
    else {
      throw new TokenException();
    }
  }

  // 检测用户是否和令牌里的用户是否一致
  public static function isValidOperate($checkedUID)
  {
    if (!$checkedUID) {
      throw new Exception('检查UID时，必须传入一个被检测的UID');
    } 
    $currentOperateUID = self::getCurrentUid();
    if ($checkedUID == $currentOperateUID) {
      return true;
    }
    return false;
  }

  // 客户端token有效性验证
  public static function verifyToken($token)
  {
    $exist = Cache::get($token);
    if ($exist) {
      return true;
    }
    else {
      return false;
    }
  }
}
?>